<template>
  <div id="eqMaintainOrderDiv">
    <GoBack content="保养工单" :backUrl="backUrl" :planId="planId" :pageSize="pageSize" :pageIndex="pageIndex" v-if="!isEmpty(planId)"></GoBack>

    <Breadcrumb content="保养工单" v-else />
    <div class="bodyContent">
      <Splitpanes horizontal class="horizontalLine">
        <Pane size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findMaintainOrderList" @keyup="keyupEnter" @search-click="findMaintainOrderList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="查询" :loading="tloading" @click="findMaintainOrderList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="快速工单" @click="addMaintainDialog()" v-if="isEmpty(planId)"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-check" content="验证" @click="verifyMaintainDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchMaintainOrder"></vxe-button>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <div class="tag-group">
                <span class="tag-group__title">【状态】：</span>
                <el-tag size="mini" v-for="item in maintainStatusList" :key="item.code" :type="getTagType(item)" effect="plain" :class="searchForm.maintainStatus==item.code?'selectedElTagClazz':'elTagClazz'" @click="clickMaintainStatus(item)">
                  {{ item.name }}
                </el-tag>
              </div>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="maintainOrderTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="maintainOrderList" :loading="tloading" @current-change="maintainOrderRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="seq" width="30" title=""></vxe-column>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column title="操作" align="center" width="150">
                <template #default="{ row }">
                  <el-link type="primary" :underline="false" @click="executeMaintain(row)">
                    <span v-if="row.maintainStatus=='15'">详情</span>
                    <span v-else>执行保养</span>
                  </el-link>
                </template>
              </vxe-column>
              <vxe-column field="maintainNo" title="保养单号" width="150">
              </vxe-column>
              <vxe-column field="maintainStatus" title="保养状态" width="150">
                <template #default="{ row }">
                  <div class="flex justify-atart">
                    <span :class="getStatusClass(row)" style="margin-right: 2px;">
                      {{ formatCommon(maintainStatusList, row.maintainStatus) }}
                    </span>
                    <el-tag type="danger" v-if="row.maintainStatus!='15'&&row.overdue>0">
                      逾期{{row.overdue}}天
                    </el-tag>
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="equiptCode" title="设备编码" width="100">
              </vxe-column>
              <vxe-column field="equiptName" title="设备名称" width="100">
              </vxe-column>
              <vxe-column field="specification" title="设备型号" width="150">
              </vxe-column>
              <vxe-column field="maintainType" title="保养类型" width="150">
                <template #default="{ row }">
                  <span>{{ formatCommon(maintainTypeList, row.maintainType) }}</span>
                </template>
              </vxe-column>
              <vxe-column field="workHours" title="保养工时" width="150">
              </vxe-column>
              <vxe-column field="maintainFee" title="保养费用" width="150">
              </vxe-column>
              <vxe-column field="startDate" title="保养开始时间" width="150">
              </vxe-column>
              <vxe-column field="endDate" title="保养完成时间" width="150">
              </vxe-column>
              <vxe-column field="planNo" title="计划编号" width="150">
              </vxe-column>
              <vxe-column field="remark" title="说明">
                <template #default="{ row }">
                  <span>{{ row.remark }}</span>
                </template>
              </vxe-column>

            </vxe-table>
            <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
        <Pane size="40">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="保养明细" name="first">
              <div class="tableBody">
                <vxe-table ref="maintainDetailTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="maintainDetailList" :loading="ploading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                  <vxe-column type="seq" width="30" title=""></vxe-column>
                  <vxe-column field="standardName" title="保养名称" width="150">
                  </vxe-column>
                  <vxe-column field="position" title="保养部位" width="150">
                  </vxe-column>
                  <vxe-column field="standard" title="保养标准" width="150">
                  </vxe-column>
                  <vxe-column field="status" title="是否保养" width="150">
                    <template #default="{ row }">
                      <span>{{ formatDetailstatus(row) }}</span>
                    </template>
                  </vxe-column>

                  <vxe-column field="remark" title="备注" width="300">
                  </vxe-column>

                </vxe-table>

              </div>
            </el-tab-pane>
            <el-tab-pane label="存档文档" name="second">
              <Documents ref="documentsRef" />
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>

  <vxe-modal v-model="isVerifyVisiable" width="45vw" show-footer :mask="false">
    <template #title>
      <span class="text-bold">验证</span>
    </template>
    <template #default>
      <div class="tableBody" style="height: 600px">
        <vxe-table ref="verifyTableRef" class="mytable-scrollbar dialogTable" border height="300px" align="center" :data="verifylList" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
          <vxe-column title="序号" width="80">
            <template #default="{ row, rowIndex, column }">
              <span>{{ rowIndex + 1 }}</span>
            </template>
          </vxe-column>
          <vxe-column title="操作" align="center" fixed="left" width="50">
            <template #default="{ row }">
              <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteVerifyMaintain(row)"></vxe-button>
            </template>
          </vxe-column>
          <vxe-column field="maintainNo" title="保养单号"></vxe-column>
          <vxe-column field="equiptCode" title="设备编码"></vxe-column>
          <vxe-column field="equiptName" title="设备名称"></vxe-column>
          <vxe-column field="maintainType" title="保养类型" width="150">
            <template #default="{ row }">
              <span>{{ formatCommon(maintainTypeList, row.maintainType) }}</span>
            </template>
          </vxe-column>
        </vxe-table>
        <div class="smallToolTitle">验证</div>
        <vxe-form ref="searchConForm" :data="verifyform" title-width="80" class="padding-sm width-100-percentage topVxeForm">
          <vxe-form-item title="是否保养" class-name="width-100-percentage">
            <vxe-radio-group v-model="verifyform.maintainStatus">
              <vxe-radio label="15">是</vxe-radio>
              <vxe-radio label="5">否</vxe-radio>
            </vxe-radio-group>
          </vxe-form-item>
        </vxe-form>

      </div>
    </template>

    <template #footer>
      <vxe-button type="text" class="button-white margin-right" @click="cancelVerifyEvent">关闭</vxe-button>
      <vxe-button type="text" class="button-blue" @click="confirmVerifyEvent">确定</vxe-button>
    </template>
  </vxe-modal>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
let { proxy }: any = getCurrentInstance();
import { AppStore } from '@/stores/store'; //'../../../stores/store';
import { isEmpty } from 'lodash';
import GoBack from '@/components/GoBackNew.vue'; //返回组件
import Documents from '@/components/Documents.vue';

let store = AppStore();

// 全局变量定义区 ==========
let searchForm = {
  searchValue: '',
  maintainStatus: ''
};
let tloading = ref(false); //加载状态
let ploading = ref(false); //加载状态
let backUrl = ref(null);
let pageSize = ref(null);
let pageIndex = ref(null);
let planId = ref(null);
let xgjlUrl = ref(null);
let maintainOrderList: any = reactive([]);
let maintainDetailList: any = reactive([]);
let maintainStatusList: any = reactive([]); //选择字典
let maintainTypeList: any = reactive([]); //选择字典
let verifylList: any = reactive([]);
let isVerifyVisiable = ref(false);

let sltMaintainOrder: any = ref({});
let activeName = ref('first');
let documentsRef: any = ref(null); //文档ref

let verifyform = reactive({
  maintainStatus: '15'
});

// 条数/页
const PageSizeList = [10, 15, 20, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  if (!isEmpty(proxy.$route.query.xgjlUrl)) {
    backUrl.value = proxy.$route.query.xgjlUrl.toString();
  }

  if (!isEmpty(proxy.$route.query.pageSize)) {
    page.pageSize = parseInt(proxy.$route.query.pageSize.toString(), 10);
    //pageSize.value = proxy.$route.query.pageSize.toString();
  }
  if (!isEmpty(proxy.$route.query.pageIndex)) {
    page.currentPage = parseInt(proxy.$route.query.pageIndex.toString(), 10);
    //pageIndex.value = proxy.$route.query.pageIndex.toString();
  }
  if (!isEmpty(proxy.$route.query.orderId)) {
    sltMaintainOrder.value.id = proxy.$route.query.orderId.toString();
  }
  if (!isEmpty(proxy.$route.query.planId)) {
    planId.value = proxy.$route.query.planId.toString();
  }
  if (!isEmpty(proxy.$route.query.xgjlUrl)) {
    xgjlUrl.value = proxy.$route.query.xgjlUrl.toString();
  }

  getDictItemsList(); //批量获取字典
  findMaintainOrderList(); // 获取质控规则表格数据
});

function clickMaintainStatus(row: any) {
  if (searchForm.maintainStatus == row.code) {
    searchForm.maintainStatus = '';
  } else {
    searchForm.maintainStatus = row.code;
  }
  findMaintainOrderList();
}

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['maintainType', 'maintainStatus'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const maintainTypes = dictTreeTypeItems.data.find((item) => item.code === 'maintainType');
  maintainTypeList.push(...maintainTypes.detailDataList);
  const maintainStatues = dictTreeTypeItems.data.find((item) => item.code === 'maintainStatus');
  maintainStatusList.push(...maintainStatues.detailDataList);
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findMaintainOrderList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findMaintainOrderList();
}
function findMaintainOrderList() {
  tloading.value = true;
  maintainOrderList.length = 0; //放入数据前清空数据
  const url = '/api/eq/eqMaintainOrder/findMaintainOrderPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        status: searchForm.maintainStatus,
        pageIndex: page.currentPage,
        pageSize: page.pageSize,
        planId: planId.value
      }
    })
    .then((res: any) => {
      maintainOrderList.push(...res.data.records);
      page.totalResult = res.data.total;
      const kn = maintainOrderList.find((k: any) => k.id == sltMaintainOrder.value.id);
      if (isEmpty(kn)) {
        maintainOrderRowClick({ row: maintainOrderList[0] }); //默认选中第一条数据
      } else {
        maintainOrderRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function maintainOrderRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltMaintainOrder.value = {};
    maintainDetailList.length = 0; //放入数据前清空数据
  } else {
    (proxy.$refs.maintainOrderTableRef as any).setCurrentRow(row);
    sltMaintainOrder.value = row;
    if (activeName.value == 'first') {
      findMaintainDetailList();
    } else if (activeName.value == 'second') {
      documentsRef.value?.findFolderList(row.maintainNo);
    }
  }
}

function tabHandleClick(tab: any) {
  if (tab.props.name == 'first') {
    findMaintainDetailList();
  } else if (tab.props.name == 'second') {
    documentsRef.value?.findFolderList(sltMaintainOrder.value.maintainNo);
  }
}

function findMaintainDetailList() {
  ploading.value = true;
  maintainDetailList.length = 0; //放入数据前清空数据
  const url = '/api/eq/eqMaintainDetail/findMaintainDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        maintainId: sltMaintainOrder.value.id
      }
    })
    .then((res: any) => {
      if (res.status.code === 1) {
        maintainDetailList.push(...res.data);
      }
      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function deleteBatchMaintainOrder() {
  const sltMaintainOrders = (proxy.$refs.maintainOrderTableRef as any).getCheckboxRecords();
  if (!(sltMaintainOrders.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delMaintainOrderList = sltMaintainOrders.filter((p: any) => !isEmpty(p.id));
        if (delMaintainOrderList.length > 0) {
          const data = { eqMaintainOrderList: delMaintainOrderList };
          const url = '/api/eq/eqMaintainOrder/batchDeleteMaintainOrderList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findMaintainOrderList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function addMaintainDialog() {
  const data = {
    pageIndex: page.currentPage.toString(),
    pageSize: page.pageSize.toString(),
    url: '/eqMaintainOrder'
  };
  proxy.$router.push({ path: '/eqMaintainEdit', query: data });
}

function executeMaintain(row: any) {
  const data = {
    id: row.id,
    pageIndex: page.currentPage.toString(),
    pageSize: page.pageSize.toString(),
    url: '/eqMaintainOrder',
    planId: planId.value,
    xgjlUrl: xgjlUrl.value
  };
  proxy.$router.push({ path: '/eqMaintainEdit', query: data });
}
//验证
function verifyMaintainDialog() {
  verifylList.length = 0;
  const selectRows = (proxy.$refs.maintainOrderTableRef as any).getCheckboxRecords();
  if (selectRows.length == 0) {
    VxeMessage('请选择设备', VxeNotifyType.error);
  } else {
    let isDialog = true;
    for (const sltRow of selectRows) {
      if (sltRow.maintainStatus !== '10') {
        isDialog = false;
      }
    }
    if (isDialog) {
      verifylList.push(...selectRows);

      isVerifyVisiable.value = true;
    } else {
      VxeMessage('保养单状态不符', VxeNotifyType.error);
    }
  }
}
async function deleteVerifyMaintain(row: any) {
  const $table = proxy.$refs.verifyTableRef as any;
  if ($table) {
    let cnt = verifylList.findIndex((a: any) => a.id == row.id);
    if (cnt > -1) {
      await $table.remove(row);
      verifylList.splice(cnt, 1);
    }
  }
}
function formatCommon(arr: any, value: any) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}

function getTagType(row: any) {
  const status = row.code;
  if (status == '0') {
    return 'warning';
  } else if (status == '5') {
    return 'success';
  } else if (status == '10') {
    return 'primary';
  } else if (status == '15') {
    return 'info';
  }
}

function getStatusClass(row: any) {
  const status = row.maintainStatus;
  if (status == '0') {
    return 'text-orange';
  } else if (status == '5') {
    return 'text-green';
  } else if (status == '10') {
    return 'text-blue';
  } else if (status == '15') {
    return 'text-black';
  }
}

function confirmVerifyEvent() {
  const url = '/api/eq/eqMaintainOrder/verifyMaintainOrder';
  const supplier = {
    eqMaintainOrderList: verifylList,
    maintainStatus: verifyform.maintainStatus
  };
  proxy.$http
    .post(url, supplier)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('成功', VxeNotifyType.success);
        findMaintainOrderList();
        isVerifyVisiable.value = false;
      } else {
        VxeMessage('失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      console.log(err);
      VxeMessage('失败', VxeNotifyType.error);
    });
}
/**关闭窗体 */
function cancelVerifyEvent() {
  isVerifyVisiable.value = false;
}
function formatDetailstatus(row: any) {
  let statusText = '';
  if (row.status == 0) {
    statusText = '未保养';
  } else if (row.status == 1) {
    statusText = '已保养';
  } else {
    statusText = '未知';
  }
  return statusText;
}
</script>

<style lang="scss" scoped>
#eqMaintainOrderDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
    }
    .horizontalLine {
      :deep(.splitpanes__splitter) {
        background-color: $base-white;
      }
    }

    // 中间table表格
    .tableBody {
      height: calc(100% - 40px - 32px);
    }
    // 质控靶值设定弹框表格
    .tableTargetBody {
      height: 600px;
      .tableTargetBodyRight {
        height: calc(100% - 2px);
        border: 1px solid #e8eaec;

        .closeBtn {
          margin-left: 720px;
        }
      }
    }

    // 右侧保存按钮
    .saveBtn {
      float: right;
      margin: 5px 10px;
    }
    .el-form {
      padding-right: 15px;
      .el-form-item--large {
        margin-bottom: 10px;
      }
      .el-button {
        padding: 5px 2px !important;
      }
      :deep(.el-input__inner) {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;
      padding: 10px;
    }
    // 最右侧质控项目设定表格
    .tableBox {
      height: calc(100% - 40px);
    }
    .elTagClazz {
      margin-left: 5px;
      cursor: pointer;
    }
    .selectedElTagClazz {
      margin-left: 5px;
      cursor: pointer;
      background-color: #89d7fc;
    }
  }
}
</style>